package com.lock.reentrantLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @PackageName:com.lock.reentrantLock
 * @ClassName:Test06
 * @Description:  tryLock(long time,TimeUnit unit)的基本使用
 * @Author: zhangxiaoyu
 * @date 2021/1/19 17:37
 */
public class Test06 {

    static class TimeLock implements Runnable{

        //定义锁对象
        private static ReentrantLock lock = new ReentrantLock();

        @Override
        public void run() {
            try {
                //如果线程1先持有线程，完成任务需要4秒钟，线程2尝试获得锁，在3秒内还没有获得锁的话，线程2会放弃
                if(lock.tryLock(3, TimeUnit.SECONDS)){   //获得锁返回true
                    System.out.println(Thread.currentThread().getName()+"获得锁，执行耗时任务");
                    Thread.sleep(4000);
                }else {
                    System.out.println(Thread.currentThread().getName()+"没有获得锁");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if(lock.isHeldByCurrentThread()){
                    lock.unlock();
                }

            }
        }
    }

    public static void main(String[] args){

        TimeLock timeLock = new TimeLock();

        Thread t1 = new Thread(timeLock);
        Thread t2 = new Thread(timeLock);

        t1.start();
        t2.start();
    }
}
